package uk.co.richardwkirk.funnels.model.data;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import uk.co.richardwkirk.funnels.model.RaceFinishers;

public class ParkrunDataLoader {

	/**
	 * Load file of results to be converted into a set of runners.
	 * 
	 * @param file
	 * @return
	 * @throws ParkrunDataLoadException 
	 */
	private String loadFromClasspath(String filename) throws ParkrunDataLoadException
	{
		// Open the file to input
		InputStream is = RaceFinishers.class.getResourceAsStream(filename);
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(isr);
		
		// Write the file contents to a string
		StringBuffer fileContents = new StringBuffer();
		String nextLine = null;
		try {
			while ((nextLine = br.readLine()) != null)
			{
				fileContents.append(nextLine).append("\n");
			}
		} catch (IOException e) {
			throw new ParkrunDataLoadException("Could not load from classpath file: " + filename, e);
		}
		return fileContents.toString();
	}
	
	private String loadFromWeb(String resourceAddress) throws ParkrunDataLoadException
	{
		try {
			URL url = new URL(resourceAddress);
			HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
			con.addRequestProperty("User-Agent", "Mozilla/4.76");
			Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
			Matcher m = p.matcher(con.getContentType());
			/* If Content-Type doesn't match this pre-conception, choose default and 
			 * hope for the best. */
			String charset = m.matches() ? m.group(1) : "ISO-8859-1";
			Reader r = new InputStreamReader(con.getInputStream(), charset);
			StringBuilder buf = new StringBuilder();
			while (true) {
			  int ch = r.read();
			  if (ch < 0)
			    break;
			  buf.append((char) ch);
			}
			return buf.toString();
		}
		catch (Exception e) {
			throw new ParkrunDataLoadException("Could not load parkrun data from web.", e);
		}
	}
	

	public String load(String resourceAddress) throws ParkrunDataLoadException {
		System.out.println("Loading park run data from [" + resourceAddress + "]");
		if (resourceAddress.contains("classpath")) {
			return loadFromClasspath(getFilenameFromClasspath(resourceAddress));
		}
		else {
			return loadFromWeb(resourceAddress);
		}
	}


	private String getFilenameFromClasspath(String resourceAddress) {
		String[] addressParts = resourceAddress.split(":");
		if (addressParts.length > 0) {
			return addressParts[1];
		}
		else {
			return resourceAddress;
		}
	}

	
}
